package com.vdg.fps;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.auth.BasicScheme;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import com.vdg.R;
import com.vdg.fps.data.AccountProxy;
import com.vdg.fps.data.FaceBookAccount;
import com.vdg.fps.data.FaceBookCookie;
import com.vdg.fps.listener.OnRequestListnener;
import com.vdg.fps.services.FPSService;
import com.vdg.fps.services.FPSService.LocalBinder;
import com.vdg.fps.ulti.ProxyAuthWebViewClient;
import com.vdg.fps.ulti.ProxyManagerment;
import com.vdg.fps.ulti.Utilities;

public class LoginActivity extends Activity {
	private WebView mWebView;
	private static String URL = "https://m.facebook.com/login.php?skip_api_login=1&api_key=145634995501895&signed_next=1&next=https%3A%2F%2Ffacebook.com%2Fv1.0%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fm.facebook.com%252Fconnect%252Flogin_success.html%26scope%3Duser_about_me%252Cuser_groups%252Cuser_friends%252Cuser_likes%252Cmanage_pages%26response_type%3Dtoken%26client_id%3D145634995501895%26ret%3Dlogin";
	// private static String URL = "http://m.dantri.com.vn";
	private static String TAG = "LoginActivity";
	private FPSService mFpsService;
	private AccountProxy mAccountProxy;
	private FrameLayout mFrmDialogLoading;
	private ServiceConnection mFpsServiceConnection = new ServiceConnection() {

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		// required for Sherlock's invalidateOptionsMenu */
		public void onServiceConnected(ComponentName name, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mFpsService = binder.getService();
		}

		public void onServiceDisconnected(ComponentName name) {
			mFpsService = null;
		}
	};

	private void initView() {
		Intent intent = getIntent();
		mWebView = (WebView) findViewById(R.id.webView);
		mFrmDialogLoading = (FrameLayout) findViewById(R.id.frm_loading);
		if (intent != null) {
			if (intent
					.getSerializableExtra(LoginSettingActivity.ACCOUNT_PROXY_KEY) != null) {
				mAccountProxy = (AccountProxy) intent
						.getSerializableExtra(LoginSettingActivity.ACCOUNT_PROXY_KEY);
				Log.v(TAG, "proxy = " + mAccountProxy.getProxyHost());
			}
		}
		// if (mAccountProxy != null) {
		// ProxyManagerment.setProxy(mWebView,
		// mAccountProxy.getProxyHost(),
		// Integer.parseInt(mAccountProxy.getProxyPort()),
		// "com.vdg.fps.ulti.ProxyManagerment");
		// }
		// // Map<String, String> header = null;
		// if (mAccountProxy != null && mAccountProxy.isIsPrivateProxy()) {
		// // UsernamePasswordCredentials creds = new
		// // UsernamePasswordCredentials(
		// // mAccountProxy.getUserName(), mAccountProxy.getPassword());
		// // Header credHeader = BasicScheme.authenticate(creds, "UTF-8",
		// // true);
		// // header = new HashMap<String, String>();
		// // Log.v(TAG,"cer = "+mAccountProxy.getUserName()
		// // +"------"+mAccountProxy.getPassword());
		// // header.put(credHeader.getName(), credHeader.getValue());
		// ProxyAuthWebViewClient client = new ProxyAuthWebViewClient(
		// mAccountProxy.getUserName(), mAccountProxy.getPassword());
		// mWebView.setWebViewClient(client);
		// // mWebView.setHttpAuthUsernamePassword(mAccountProxy.getProxyHost(),
		// "", mAccountProxy.getUserName(),mAccountProxy.getPassword());
		// }

		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return super.shouldOverrideUrlLoading(view, url);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				CookieManager cookieManager = CookieManager.getInstance();
				if (url.contains("login_success.html")) {
					if (!url.contains("client_id")) {
						String cookie = cookieManager
								.getCookie("https://facebook.com");
						if (cookie != null) {
							Log.v(TAG, "url == " + url);
							Log.v(TAG, "cookie " + "-------------- " + cookie);
							String[] arrCookies = cookie.split(";");
							if (arrCookies.length >= 8) {
								final FaceBookAccount account = new FaceBookAccount();
								account.setCookies(new FaceBookCookie(cookie));
								account.setCookiesExpires(System
										.currentTimeMillis()
										+ 2
										* 364
										* 24
										* 60 * 60 * 1000);
								if (mAccountProxy != null) {
									account.setProxy(mAccountProxy);
								}
								mFrmDialogLoading.setVisibility(View.VISIBLE);
								mFpsService.setUpAccount(LoginActivity.this,
										account, new OnRequestListnener() {

											@Override
											public void onSuccess(
													String response) {
												// TODO Auto-generated method
												// stub
//												mFrmDialogLoading
//														.setVisibility(View.GONE);
											}

											@Override
											public void onFailed(int errorCode) {
												// TODO Auto-generated method
												// stub
//												mFrmDialogLoading
//														.setVisibility(View.GONE);
											}
										});
							}
						}
					} else {
						Log.v(TAG, "url == " + url);
					}
				}
				super.onPageFinished(view, url);
			}
		});
		CookieManager.getInstance().removeAllCookie();
		mWebView.loadUrl(URL);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		Intent fpsServiceIntent = new Intent(this, FPSService.class);
		bindService(fpsServiceIntent, mFpsServiceConnection, BIND_AUTO_CREATE);
		initView();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unbindService(mFpsServiceConnection);
		super.onDestroy();
	}
}
